package cn.cena.user.service.impl;

import cn.cena.basic.Exception.MyException;
import cn.cena.basic.util.AjaxResult;
import cn.cena.basic.util.HttpClientUtils;
import cn.cena.basic.util.MD5Utils;
import cn.cena.basic.util.StrUtils;
import cn.cena.user.Constant.UserConstant;
import cn.cena.user.domain.Logininfo;
import cn.cena.user.domain.User;
import cn.cena.user.domain.WxUser;
import cn.cena.user.dto.LoginDto;
import cn.cena.user.mapper.LogininfoMapper;
import cn.cena.user.mapper.UserMapper;
import cn.cena.user.mapper.WxUserMapper;
import cn.cena.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ILoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(LoginDto loginDto) {

        // 判断是否为空
        if(StringUtils.isEmpty(loginDto.getUsername())
                ||StringUtils.isEmpty(loginDto.getPassword())
                ||StringUtils.isEmpty(loginDto.getType())){
            throw new MyException("请完善登录信息");
        }
        // 判断用户是否存在
        Logininfo logininfo = logininfoMapper.findByUsernameAndType(loginDto);
        if (logininfo == null){
            throw new MyException("用户名错误");
        }

        // 判断密码是否正确
        // 获取数据库中密码及盐值
        String logininfoPassword = logininfo.getPassword();
        String salt = logininfo.getSalt();

        // 将用户输入密码加盐加密作比较
        String byMd5 = MD5Utils.encrypByMd5(salt + loginDto.getPassword());
        if(!logininfoPassword.equals(byMd5)){
            throw new MyException("密码错误");
        }
        // 登录成功
        String token = UUID.randomUUID().toString(); // 随机生成字符串作为key
        // 存入redis
        redisTemplate.opsForValue().set(token,logininfo ,30 , TimeUnit.MINUTES );

        // 存入map
        HashMap<String, Object> map = new HashMap<>();

        map.put("token", token);
        // 将用户敏感信息清除，避免前端看到
        logininfo.setPassword("");
        logininfo.setPhone("");
        logininfo.setEmail("");
        logininfo.setSalt("");
        map.put("logininfo", logininfo);
        return map;
    }

    @Override
    public AjaxResult loginWechat(Map<String, String> params) {
        // 获取code
        String code = params.get("code");
        //判断code是否为空
        if(code == null){
            throw new MyException("授权码不存在");
        }

        // 通过code获取token令牌，为json格式字符串
        /**
         * {
         "access_token": "ACCESS_TOKEN",
         "expires_in": 7200,
         "refresh_token": "REFRESH_TOKEN",
         "openid": "OPENID",
         "scope": "SCOPE"
         }

         */
        String strObj = HttpClientUtils.httpGet(UserConstant.TOKEN_BY_CODE.replace("APPID", UserConstant.APPID)
                .replace("SECRET", UserConstant.SECRET)
                .replace("CODE", code));

        // JSON格式字符串转换成JSON对象
        JSONObject jsonObject = JSONObject.parseObject(strObj);

        // 获取access_token
        String accessToken = jsonObject.getString("access_token");
        // 获取openid
        String openid = jsonObject.getString("openid");

        // 根据openid查询
        WxUser wxUser = wxUserMapper.findByOpenid(openid);
        // 判断是否为空，若不为空，且user_id存在，则有登录信息，免密登录
        if(wxUser != null && wxUser.getUser_id() != null){
            // 登录成功，登录信息logininfo存入redis
           Logininfo logininfo = logininfoMapper.findByUserId(wxUser.getUser_id()); // 对象存到redis需要序列化
           String token = UUID.randomUUID().toString();
           redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

           // 将token和logininfo存入map返回前端页面，用于存入localStorge
            Map<String, Object> map = new HashMap<>();
            map.put("token",token );
            // 将用户机密信息隐藏
            logininfo.setSalt("");
            logininfo.setEmail("");
            logininfo.setPhone("");
            logininfo.setPassword("");
            map.put("logininfo",logininfo );

            return AjaxResult.result().setResultObj(map);

        }else {
            // 没有登录信息，将返回的token和openid返回给前端
            String param = "?accessToken="+accessToken + "&openId=" + openid;
            return AjaxResult.result().setSuccess(false).setResultObj(param);
        }
    }

    /**
     * 微信登录绑定
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> binderWechat(Map<String, String> params) {
        String phone = params.get("phone");
        String accessToken = params.get("accessToken");
        String verifyCode = params.get("verifyCode");
        String openId = params.get("openId");
        // 判断是否为空
        if(StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(openId)){
            throw new MyException("请完善绑定信息");
        }
        // 判断验证码是否过期
        Object tmpCode = redisTemplate.opsForValue().get(UserConstant.BINDER_PREFIX + phone);

        if(tmpCode == null){
            throw new MyException("验证码已过期，请重新发送");
        }
        // 若未过期，判断验证码是否正确
        String code = tmpCode.toString().split("-")[1];
        if(!verifyCode.equalsIgnoreCase(code)){ // 不区分大小写equalsIgnoreCase
            throw new MyException("验证码错误，请重新输入");
        }
        // 判断手机号是否被注册
        // 手机号是否被注册
        User tmpuser = userMapper.findByphone(phone);
        User user = null;
        Logininfo logininfo = null;
        if (tmpuser != null){ // 手机号已注册
            // 判断手机号是否绑定,根据userid是否能找到Wx_user
            WxUser wxUser = wxUserMapper.findByUserId(tmpuser.getId());
            if (wxUser.getOpenid() != null){
                throw new MyException("该手机号已绑定");
            }else {
                user = tmpuser;
                logininfo = logininfoMapper.findByUserId(user.getId());
            }

        }else { // 手机号没注册
            // 生成User、logninfo
            user = setUser(phone);
            logininfo = setLogininfo(user);

            // 先保存logininf返回自增主键
            logininfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }

        // 获取Wx_User
        String strObj = HttpClientUtils.httpGet(UserConstant.WX_USER.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId));
        WxUser wxUser = setWxUser(strObj,user);
        wxUserMapper.save(wxUser);
        // 登录成功
        String token = UUID.randomUUID().toString(); // 随机生成字符串作为key
        // 存入redis
        redisTemplate.opsForValue().set(token,logininfo ,30 , TimeUnit.MINUTES );

        // 存入map
        HashMap<String, Object> map = new HashMap<>();

        map.put("token", token);
        // 将用户敏感信息清除，避免前端看到
        logininfo.setPassword("");
        logininfo.setPhone("");
        logininfo.setEmail("");
        logininfo.setSalt("");
        map.put("logininfo", logininfo);
        return map;
    }

    /**
     * {
     "openid": "OPENID",
     "nickname": "NICKNAME",
     "sex": 1,
     "province": "PROVINCE",
     "city": "CITY",
     "country": "COUNTRY",
     "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
     "privilege": ["PRIVILEGE1", "PRIVILEGE2"],
     "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
     }
        获取WxUser
     * @param strObj
     * @param user
     * @return
     */
    private WxUser setWxUser(String strObj, User user) {
        JSONObject jsonObject = JSONObject.parseObject(strObj);
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setAddress("");
        wxUser.setSex(1);
        wxUser.setUnionid(jsonObject.getString("unionid"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUser_id(user.getId());
        return wxUser;
    }

    private Logininfo setLogininfo(User user) {
        Logininfo logininfo = new Logininfo();

        // 按属性名进行拷贝
        BeanUtils.copyProperties(user, logininfo);

        return logininfo;
    }

    private User setUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        user.setEmail(phone);
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String password = MD5Utils.encrypByMd5(salt + 1);
        user.setPassword(password);

        return user;
    }
}
